package com.mengchengnet.chaperonage.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.Constants;
import com.mengchengnet.chaperonage.util.OrderInfoUtil2_0;
import com.mengchengnet.chaperonage.util.PayResult;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ValueUtil;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.CircleImageView;
import com.mengchengnet.chaperonage.view.RatingBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyou.view.segmentedbar.Segment;
import com.zhouyou.view.segmentedbar.SegmentedBarView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

import static com.mengchengnet.chaperonage.wxapi.WeChatPayService.genPackageSign;


public class OrderActivity extends BaseActivity implements View.OnClickListener{

    private TextView tvDescription,tv_name,tv_address,tv_age,tv_work;
    private int maxDescriptionLine = 4; //TextView默认最大展示行数
    private TextView tvExpand;
    private TextView tv_skill;
    private String skill="";
    private boolean isDescriptionExpanded = false;
    private Button btn_order;
    private String appId,partnerid,nonce_str,prepay_id,timestamp,sign;
    private String name,address,age,workAge,head,descrpsion,price,careId;
    private int star;
    private CircleImageView headIcon;
    private LinearLayout lin_comment,lin_service,lin_start,lin_address;
    private TextView tv_number;//用户评论的数量
    private RadioGroup radioGroup;
    private TextView tv_tip,tv_price,tv_time;
    private RatingBar ratingBar;
    private ImageView iv_add,iv_reduce;
    private EditText ed_number;
    private TextView tv_money,tv_userName;
    private LinearLayout lin_weixin,lin_alipay;
    private ImageView iv_weixin,iv_alipay;
    private static final String APPID="2017082408349943";
    private RequestQueue requestQueue;
    private String startTime="";//开始时间
    public static final String RSA_PRIVATE="";
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC9JQANzlfLyFN7PF652IH22T6BiPwo01R+ojnkEys/n5aEEFqpmMa7MxfbooDGYNGG4HmgShr4+PTXTsxJgK0+29RzxXEbdkuiL93PWoAk7nby3IK3NNDXF4hGa9dHWuZuJJLg0uP/B/+ne60m1DDOxGcpwdIs/tiJTvvKoxetY7iozs4k4JMNkdK7ujNgeA1f3sasQVwMtM4npL3D8H+3n2D4XmJLeY/z7Wjc1klEaqyDXDYWM8NZD3DBgx0Z5TM2mv41buD8rSLxxiTF6xzpfLA8/wWdQ9MNdnOGPkWYoEIJRjwlaSv/cVYznb3JBRU4l/oQYR4qy7l8PEhyU11xAgMBAAECggEBALSlIegNqsx2B0Ur40yb+4RG9+u/aRWUwJ4xUhkCNcwOHzMCa5SO1T71DVQ3X8YXsgWfXoo4PIqNO0pnd7S7sLrYOZBYgi44TQQZsz7WsIyVNAW/lRhk2RCU6RJY7MK5jlqjk6QlxptMiF7tP/JVtkfETMMU2icfPq/lP5XJLlPpweuWyNTrsus5m5OMBcpGRSdvMaqndacIXf/VJvmC2m6kcbbENd8wNe16KIIkuh1E0ivBz11XTdiVPvftZ+ah9UrFh5Oud/t0vaBjfw8uhUQtwTvdJ+fpLDIqkmXXuys1hQKnJ9Nq0T0x3eucVnmzhELeTomZ7G0crPE2dWBF+AECgYEA+0UDWwqNOP2GLN2lsG+O/+8CHlOJr6W7hmtr6Im2gH/zYwLbV6eP2DqaFPbOQr4d2TiHs+VFL7yFUG91qRreU32NnFrO0v2ZRlW6CeGyj8kD6qKo7wsLz4IJBm6LQfKWXBq3XwTJ6HNyBAAjEneCXCOBNaKgfnvZQY3i+dZPelUCgYEAwLSTvgx/0Ze3VXQq60qk7qDPupBeixmAU74bW3MebkMxnk5KDq8DSJ3n6q/LDQ93TEmzjAK0Sh+JgaQQM8iKbKC62mvxJvQpnbN4WDKP5SHVaY4rzHkFJoIsOsSMqZdxW35YPoYbtgiU76jFQwxdj8OKZLk8NvN9nhdM2Lmc6q0CgYBqD2xmLmMD7keHgptgiQZUU3+Sa3KPuKYaDBfFVPO688c5QMhzDGB0RfAp7y+LDpKs0Oa+8YStrKadGB8THStBFJsEp3PrrW3YOXFIoILtnEzR6oziMchvc5T5qQmQ8aO0Bvbl3bCYNLqoo6IqNlXJLJdqm1Whbgd7Wze2e1aa7QKBgQCLzfYpuPO6YTFWw7KnhT3nCa/rD/YnQFcDajZ6wCfhosoKqY283WeqdTTd5K+RSBkqtYWXHBckd4DRFu/SQbl7WZh2Aj2wHw9aI+w5QGV4vHUR4V0ROPNtnp7r+9B48TACSsVGhxDvnYY/4NdL71qphBmRPXnb/Aa0fP75dJ/M+QKBgEv/mOtBANcmz/hssYvyRb2rKjcaKQxZd+CaPuCVe1sxsQC7Qm9MSRzF/9+18C1MJDco5BNGJ5iPmMawDE5hz6D3HT9OywbTsgX9VArNRPPoz1hr6kGkOf1wOD1gg85l9aCVWl/FGKEDKZqMo8pxlfVIc1vaSmcZtGWPB3m+q+qE";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_PAY_FLAG2 = 2;
    private IWXAPI api;
    private LinearLayout lin_type;
    private static final String TAG = "OrderActivity";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(OrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent =new Intent(OrderActivity.this, ALiPayResult.class);
                        intent.putExtra("isSucess","0");
                        startActivity(intent);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(OrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        Intent intent =new Intent(OrderActivity.this, ALiPayResult.class);
                        intent.putExtra("isSucess","1");
                        startActivity(intent);
                    }
                    break;

                }
                case SDK_PAY_FLAG2:{
                    //Toast.makeText(OrderActivity.this, "调起微信支付", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "appId: "+appId);
                    Log.e(TAG, "partnerid: "+partnerid);
                    Log.e(TAG, "prepay_id: "+prepay_id);
                    Log.e(TAG, "nonce_str: "+nonce_str);
                    Log.e(TAG, "timestamp: "+timestamp);
                    Log.e(TAG, "sign: "+sign);
                    PayReq request = new PayReq();
                    request.appId = appId;
                    request.partnerId = partnerid;
                    request.prepayId= prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr= nonce_str;
                    request.timeStamp= timestamp;
                    request.sign= sign;
                    api.sendReq(request);
                }
                case 3:
                    tv_skill.setText(skill);
                    break;

            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        api = WXAPIFactory.createWXAPI(this, null);
        // 将该app注册到微信
        api.registerApp(Constants.APP_ID);
        initView();

    }

    private void initView() {
        requestQueue= Volley.newRequestQueue(getApplication());
        toolbarState = TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("下单");
        name=getIntent().getStringExtra("name");
        address=getIntent().getStringExtra("address");
        age=getIntent().getStringExtra("age");
        workAge=getIntent().getStringExtra("workAge");
        head=getIntent().getStringExtra("head");
        descrpsion=getIntent().getStringExtra("evaulate");
        price=getIntent().getStringExtra("price");
        careId=getIntent().getStringExtra("careId");
        star=getIntent().getIntExtra("star",5);

        btn_order= (Button) findViewById(R.id.order_produceOrder);
        btn_order.setOnClickListener(this);

        tvDescription = (TextView) findViewById(R.id.tv_description);
        tvDescription.setText(descrpsion);

        headIcon= (CircleImageView) findViewById(R.id.iv_photo);
        ViewUtil.showImageView(this,headIcon,head);

        tv_name= (TextView) findViewById(R.id.tv_name);
        tv_name.setText(name);

        tv_address= (TextView) findViewById(R.id.tv_hometown);
        tv_address.setText(address);

        tv_age= (TextView) findViewById(R.id.tv_age);
        tv_age.setText(age);

        tv_work= (TextView) findViewById(R.id.tv_work_time);
        tv_work.setText(workAge);

        tv_price= (TextView) findViewById(R.id.order_tv_price);
        tv_price.setText(price);

        tvExpand = (TextView) findViewById(R.id.tv_expand);
        tvExpand.setOnClickListener(this);

        tvDescription.post(new Runnable() {

            @Override
            public void run() {
                tvDescription.setHeight(tvDescription.getLineCount() > maxDescriptionLine ? tvDescription.getLineHeight() * maxDescriptionLine : tvDescription.getLineHeight() * tvDescription.getLineCount());
                tvExpand.setVisibility(tvDescription.getLineCount() > maxDescriptionLine ? View.VISIBLE : View.GONE);
            }
        });

        lin_comment= (LinearLayout) findViewById(R.id.order_lin_comment);
        lin_comment.setOnClickListener(this);
        tv_number= (TextView) findViewById(R.id.order_tv_commentNumber);
        tv_number.setText(getIntent().getStringExtra("commentCount"));
        lin_service= (LinearLayout) findViewById(R.id.order_lin_service);
        lin_service.setOnClickListener(this);

        tv_tip= (TextView) findViewById(R.id.order_tv_target);

        radioGroup= (RadioGroup) findViewById(R.id.rg_trans_amount);
        addview(radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                int id=radioGroup.getCheckedRadioButtonId();
                RadioButton button = (RadioButton) findViewById(id);
                String result= button.getText()+"";

                if (result.equals("全天陪护A")){
                    tv_tip.setText(R.string.tip_target3);
                    tv_price.setText("160");
                    tv_money.setText(Integer.parseInt(tv_price.getText().toString())*Integer.parseInt(ed_number.getText().toString())+"");
                }else if(result.equals("全天陪护B")){
                    tv_tip.setText(R.string.tip_target2);
                    tv_price.setText("180");
                    tv_money.setText(Integer.parseInt(tv_price.getText().toString())*Integer.parseInt(ed_number.getText().toString())+"");
                }else {
                    tv_tip.setText(R.string.tip_target);
                    tv_price.setText("200");
                    tv_money.setText(Integer.parseInt(tv_price.getText().toString())*Integer.parseInt(ed_number.getText().toString())+"");
                }
            }
        });

        lin_start= (LinearLayout) findViewById(R.id.order_lin_start);
        lin_start.setOnClickListener(this);
        tv_time= (TextView) findViewById(R.id.order_tv_time);

        iv_add= (ImageView) findViewById(R.id.order_increase);
        iv_reduce= (ImageView) findViewById(R.id.order_decrease);
        ed_number= (EditText) findViewById(R.id.order_edtext);
        ed_number.setText("1");
        ed_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(charSequence.length()>0){
                    if (isDigits(tv_price.getText().toString())){
                        tv_money.setText(String.valueOf(Integer.parseInt(tv_price.getText().toString())*Integer.parseInt(String.valueOf(charSequence))));
                    }else{
                        tv_money.setText(String.valueOf(Double.parseDouble(tv_price.getText().toString())*Integer.parseInt(String.valueOf(charSequence))));
                    }

                }else {
                    tv_money.setText("0");
                }


            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        iv_reduce.setOnClickListener(this);
        iv_add.setOnClickListener(this);

        tv_money= (TextView) findViewById(R.id.order_money);
        tv_money.setText(Float.parseFloat(tv_price.getText().toString())*Integer.parseInt(ed_number.getText().toString())+"");

        lin_address= (LinearLayout) findViewById(R.id.order_address);
        lin_address.setOnClickListener(this);

        tv_userName= (TextView) findViewById(R.id.order_name);
        lin_alipay= (LinearLayout) findViewById(R.id.order_lin_alipay);
        lin_weixin= (LinearLayout) findViewById(R.id.order_lin_weixin);
        iv_alipay= (ImageView) findViewById(R.id.order_icon_alipay);
        iv_weixin= (ImageView) findViewById(R.id.order_icon_weixin);
        lin_weixin.setOnClickListener(this);
        lin_alipay.setOnClickListener(this);
        tv_skill= (TextView) findViewById(R.id.order_tv_skill);//护理技能
        ratingBar= (RatingBar) findViewById(R.id.order_ratingBar);
        ratingBar.setStar(star);
        ratingBar.setStarCount(star);
        SegmentedBarView barView = (SegmentedBarView) findViewById(R.id.barView);
        ArrayList<Segment> segments = new ArrayList<>();
        Segment segment = new Segment("text1", "", Color.parseColor("#EF3D2F"));
        segments.add(segment);
        Segment segment2 = new Segment("text2", "", Color.parseColor("#8CC63E"));
        segments.add(segment2);
        Segment segment3 = new Segment("text3","",Color.parseColor("#EF3D2F"));
        segments.add(segment3);
        //barView.setValueWithUnit(13.96f, "10<sup>12</sup>/l");
        //barView.setSegmentSideRule(SegmentedBarViewSideRule.average);//通过代码设置规则
        //barView.setValue(13.96f);
        //barView.setValue(13.96f,"Optimal");
        barView.setBarHeight(100);
        barView.setSegments(segments);
        //control.setText("类型一"+"|"+"类型2");
        //获取陪护个人技能
        getSkill();
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.order_produceOrder:
                if (iv_alipay.getVisibility()==View.VISIBLE){
                    //getOrderInfo2();
                    //payV2();
                    Toast.makeText(this, "支付宝目前不可用！", Toast.LENGTH_SHORT).show();
                }
                if (iv_weixin.getVisibility()==View.VISIBLE){
                    if (!startTime.isEmpty()){
                        getOrderInfo();
                    }else{
                        Toast.makeText(this, "请先选择陪护开始时间！", Toast.LENGTH_SHORT).show();
                    }

                }
                break;
            case R.id.tv_expand:
                isDescriptionExpanded = !isDescriptionExpanded;

                final int deltaValue;//默认高度，即前边由maxLine确定的高度
                final int startValue = tvDescription.getHeight();//起始高度

                //若当前是展开状态，则将其收起；若当前是收起状态，则将其展开
                if (isDescriptionExpanded) {
                    tvExpand.setText("收起");
                    deltaValue = tvDescription.getLineHeight() * tvDescription.getLineCount() - startValue;
                } else {
                    tvExpand.setText("全文");
                    deltaValue = tvDescription.getLineHeight() * maxDescriptionLine - startValue;
                }

                tvDescription.setHeight(startValue + deltaValue);
                break;
            case R.id.order_lin_comment:
                if (!tv_number.getText().toString().equals("0")){
                    Intent com=new Intent(this,CommentActivity.class);
                    com.putExtra("careId",careId);
                    startActivity(com);
                }else{
                    Toast.makeText(this, "暂无评价", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.order_lin_service:

                Intent intent=new Intent(this,ServiceActivity.class);
                intent.putExtra("careId",careId);
                startActivity(intent);
                break;
            case R.id.order_lin_start:
                Intent t=new Intent();
                t.setClass(this,CalanderActivity.class);
                t.putExtra("mode","1");
                startActivityForResult(t,0);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.order_address:
                Intent t1=new Intent();
                t1.setClass(this,AddressActivity.class);
                startActivityForResult(t1,1);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.order_decrease:
                int now=Integer.parseInt(ed_number.getText().toString());
                if (now>2 ){
                    ed_number.setText(String.valueOf(now-1));
                    //tv_money.setText((now-1)*Integer.parseInt(tv_price.getText().toString())+"");
                    if (isDigits(tv_price.getText().toString())){
                        tv_money.setText((now-1)*Integer.parseInt(tv_price.getText().toString())+"");
                    }else {
                        tv_money.setText(String.valueOf((now-1)*Double.parseDouble(tv_price.getText().toString())));
                    }
                }else if(now==2){
                    ed_number.setText(String.valueOf(now-1));
                    iv_reduce.setBackgroundResource(R.mipmap.no_delte_1);
                    //tv_money.setText((now-1)*Integer.parseInt(tv_price.getText().toString())+"");
                    if (isDigits(tv_price.getText().toString())){
                        tv_money.setText((now-1)*Integer.parseInt(tv_price.getText().toString())+"");
                    }else {
                        tv_money.setText(String.valueOf((now-1)*Double.parseDouble(tv_price.getText().toString())));
                    }
                }else {
                    ed_number.setText(String.valueOf(1));
                    iv_reduce.setBackgroundResource(R.mipmap.no_delte_1);
                    //tv_money.setText(Integer.parseInt(tv_price.getText().toString())+"");
                    tv_money.setText(String.valueOf(tv_price.getText().toString()));

                }


                break;
            case R.id.order_increase:
                int now2=Integer.parseInt(ed_number.getText().toString());
                ed_number.setText(String.valueOf(now2+1));
                iv_reduce.setBackgroundResource(R.mipmap.date_delte_1);
                if (isDigits(tv_price.getText().toString())){
                    tv_money.setText((now2+1)*Integer.parseInt(tv_price.getText().toString())+"");
                }else {
                    tv_money.setText(String.valueOf((now2+1)*Double.parseDouble(tv_price.getText().toString())));
                }


                break;
            case R.id.order_lin_alipay:
                iv_alipay.setVisibility(View.VISIBLE);
                iv_weixin.setVisibility(View.INVISIBLE);
                break;

            case R.id.order_lin_weixin:
                iv_alipay.setVisibility(View.INVISIBLE);
                iv_weixin.setVisibility(View.VISIBLE);
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 0:
                if (resultCode==RESULT_OK){
                    String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
                    if(!result.isEmpty()){
                        tv_time.setText(result);
                        //startTime= DateUtils.change(result);
                        startTime=result;
                        Log.e("订单界面", "选择日期的时间戳："+startTime);

                    }
                }
                break;
            case 1:
                if (resultCode==RESULT_OK){
                    String result = data.getExtras().getString("name");//得到新Activity 关闭后返回的数据
                    if(!result.isEmpty()){
                        tv_userName.setText(result);
                    }
                }

                break;
        }

    }


    private void getOrderInfo(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getOrder,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("获取订单信息", "获取订单信息接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                //Toast.makeText(OrderActivity.this, "订单生成成功", Toast.LENGTH_SHORT).show();
                                JSONObject jj=jsonObject.getJSONObject("data");
                                JSONObject jjo=jj.getJSONObject("config");

                                 appId=jjo.getString("appid");
                                 partnerid=jjo.getString("partnerid");
                                 nonce_str=jjo.getString("noncestr");
                                 prepay_id=jjo.getString("prepayid");
                                 timestamp=jjo.getString("timestamp");
                                 //sign=jjo.getString("sign");
                                List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                                signParams.add(new BasicNameValuePair("appid", appId));
                                signParams.add(new BasicNameValuePair("noncestr", nonce_str));
                                signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
                                signParams.add(new BasicNameValuePair("partnerid", partnerid));
                                signParams.add(new BasicNameValuePair("prepayid", prepay_id));
                                signParams.add(new BasicNameValuePair("timestamp", timestamp));
                                sign=genPackageSign(signParams);
                                Log.i(TAG, "appid: "+appId );
                                Log.i(TAG, "partnerid: "+partnerid );
                                Log.i(TAG, "nonce_str: "+nonce_str );
                                Log.i(TAG, "prepay_id: "+prepay_id );
                                Log.i(TAG, "timestamp: "+timestamp );
                                Log.i(TAG, "自己生成的sign: "+sign );

                                mHandler.sendEmptyMessage(2);

                            }
                            else {
                                Toast.makeText(OrderActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(OrderActivity.this, arg0.toString(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("loginId", PreferenceUtil.getString(getApplication(),"userId"));
                map.put("personId", careId);
                map.put("startTime", startTime);
                map.put("ServiceMode", "12");
                map.put("serviceTimes", ed_number.getText().toString());
                map.put("pay_style", "1");
                map.put("totalMoney", tv_money.getText().toString());
                Log.e("订单", "startTime:"+startTime);
                Log.e("订单", "serviceTimes:"+ed_number.getText().toString());
                Log.e("订单", "totalMoney:"+tv_money.getText().toString());
                Log.e("订单", "userId:"+PreferenceUtil.getString(getApplication(),"userId"));
                Log.e("订单", "startTime:"+startTime);
                Log.e("订单", "careId:"+careId);
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    private void getOrderInfo2(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getOrder,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("获取订单信息", "获取订单信息接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                //Toast.makeText(OrderActivity.this, "成功", Toast.LENGTH_SHORT).show();

                            }
                            else {
                                Toast.makeText(OrderActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(OrderActivity.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("loginId", PreferenceUtil.getString(getApplication(),"userId"));
                map.put("personId", careId);
                map.put("startTime", startTime);
                map.put("ServiceMode", "12");
                map.put("serviceTimes", ed_number.getText().toString());
                map.put("pay_style", "2");
                map.put("totalMoney", tv_money.getText().toString());
                Log.e("订单", "startTime:"+startTime);
                Log.e("订单", "serviceTimes:"+ed_number.getText().toString());
                Log.e("订单", "totalMoney:"+tv_money.getText().toString());
                Log.e("订单", "userId:"+PreferenceUtil.getString(getApplication(),"userId"));
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    /**
     * 支付宝支付业务
     *
     * @param
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
        Log.e(TAG, "支付宝orderInfo: "+orderInfo);
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void getSkill(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getCareInfo,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("获取陪护技能信息", "获取陪护技能信息接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                JSONArray array=jsonObject.getJSONArray("skill_list");
                                Log.e("ppp", "集合长度: "+array.length());
                                if (array.length()>0){
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject obj = array.getJSONObject(i);
                                        String name = obj.getString("name");
                                        String brief = obj.getString("brief");
                                        skill=skill+name+",";

                                    }
                                    mHandler.sendEmptyMessage(3);
                                }else {
                                    mHandler.sendEmptyMessage(1);
                                }
                            }
                            else {
                                Toast.makeText(OrderActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(OrderActivity.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("zescort_id", getIntent().getStringExtra("careId"));
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }


    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
      //判断是否是整数
    public static boolean isDigits(String str) {
        return str.matches("[-+]?[0-9]*");
    }

    public List<String> getListSize(){
        List<String>list=new ArrayList<String>();
        list.add("服装");
        list.add("玩具");
        list.add("饰品");
        list.add("饰品");
        return list;
    }

    //动态添加视图
    public void addview(RadioGroup radiogroup){

        int index=0;
        for(String ss:getListSize()){

            RadioButton  button=new RadioButton(this);
            setRaidBtnAttribute(button,ss,index);

            radiogroup.addView(button);

            LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) button
                    .getLayoutParams();
            layoutParams.setMargins(0, 0,  ValueUtil.dp2px(this,10), 0);//4个参数按顺序分别是左上右下
            button.setLayoutParams(layoutParams);
            index++;
        }


    }

    private void setRaidBtnAttribute( final RadioButton codeBtn, String btnContent, int id ){
        if( null == codeBtn ){
            return;
        }
        codeBtn.setBackgroundResource(R.drawable.bg_radio_left_button);
        //codeBtn.setTextColor(this.getResources().getColorStateList(R.drawable.color_radiobutton));
        codeBtn.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        //codeBtn.setTextSize( ( textSize > 16 )?textSize:24 );
        codeBtn.setId( id );
        codeBtn.setText( btnContent );
        //codeBtn.setPadding(2, 0, 2, 0);

        codeBtn.setGravity( Gravity.CENTER );
        codeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //DensityUtilHelps.Dp2Px(this,40)
        LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT , LinearLayout.LayoutParams.MATCH_PARENT );

        codeBtn.setLayoutParams( rlp );
    }

}